package level.editor.control.layer;

import java.awt.Dimension;
import java.util.TreeMap;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import level.editor.control.collision.CollisionLayer;
import level.editor.control.collision.CollisionLayerBlock;
import level.editor.control.main.Main;
import level.editor.control.main.MainScroll;
import level.editor.control.main.MainTabbed;
import level.editor.control.object.ObjectLayer;
import level.editor.control.object.ObjectLayerBlock;
import level.editor.control.tile.TileLayer;
import level.editor.control.tile.TileLayerBlock;
import level.editor.view.action.ActionConstants;
import level.editor.view.group.Item;

public class LayerControl extends Item implements ChangeListener
{

	public LayerControl(MainTabbed mainTabbed)
	{
		super(null);
		setMinimumSize(new Dimension(400, 100));
		setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
		setName("Layer Manager");
		setIcon(new ImageIcon(ActionConstants.ICON_DIR + "layer.png"));
		layerBlocks = new TreeMap<Integer, LayerBlock>();
		mainTabbed.addChangeListener(this);
		init(((MainScroll) mainTabbed.getSelectedComponent()).getMain());
	}

	public void setSelected(TileLayerBlock block)
	{
		for (Integer i : layerBlocks.keySet())
		{
			if (layerBlocks.get(i) != block)
			{
				if (layerBlocks.get(i) instanceof TileLayerBlock)
					((TileLayerBlock) layerBlocks.get(i)).setSelected(false);
			}
		}
	}

	public void updateChange(MainTabbed mainTabbed)
	{
		removeAll();
		init(((MainScroll) mainTabbed.getSelectedComponent()).getMain());
	}

	@Override
	public void stateChanged(ChangeEvent e)
	{
		if (e.getSource() instanceof MainTabbed)
		{
			updateChange((MainTabbed) e.getSource());
		}
	}

	private void init(Main main)
	{
		TreeMap<Integer, Layer> layers = main.getLayers();
		for (Integer i : layers.keySet())
		{
			Layer layer = layers.get(i);
			LayerBlock block = null;
			if (layer instanceof TileLayer)
			{
				block = new TileLayerBlock((TileLayer) layer);
			}
			else if (layer instanceof CollisionLayer)
			{
				add(Box.createGlue());
				block = new CollisionLayerBlock((CollisionLayer) layer);
			}
			else if (layer instanceof ObjectLayer)
			{
				block = new ObjectLayerBlock((ObjectLayer) layer);
			}
			add(block);
			block.registerMain(main);
			layerBlocks.put(i, block);
		}
	}

	private TreeMap<Integer, LayerBlock> layerBlocks;

}
